//
//  MGCustomPickView.m
//  MGPublic
//
//  Created by lhongl on 2025/10/24.
//

#import "MGCustomPickView.h"
#import <Masonry/Masonry.h>
#import "MGMacros.h"
@interface MGCustomPickView () <UIPickerViewDataSource,UIPickerViewDelegate>
/// 按钮
@property(nonatomic, strong) UIToolbar *toolbar;

/// pickView
@property (nonatomic, strong) UIPickerView *pickerView;

///customType
@property (nonatomic, strong) NSArray<NSString *> *itemTitles;

/// 选择类型
@property (nonatomic, assign) MGPickerViewType type;

/// 选中时间
@property (nonatomic, strong) MGCustomPickViewDateSelectModel *selectModel;

/// 其实时间
@property (nonatomic, assign) NSInteger startYear;

/// 天数范围
@property (nonatomic, assign) NSInteger dayRange;

/// 事件选中结果
@property (nonatomic, copy) NSString *result;

/// 年的范围
@property (nonatomic, assign) NSInteger yearRange;

@end

@implementation MGCustomPickView

- (instancetype)initCustomWithTitles:(NSArray <NSString *>*)items index:(NSInteger)index {
    if (self = [super init]) {
        self.itemTitles = items;
        self.type = customType;
        if (index > 0) {
            [self.pickerView selectRow:index inComponent:0 animated:NO];
            [self pickerView:self.pickerView didSelectRow:index inComponent:0];
        }
    }
    return self;
}

- (instancetype)initCustomWithType:(MGPickerViewType)type {
    if (self = [super init]) {
        self.type = type;
        [self setDefaultInit];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpView];
    // Do any additional setup after loading the view.
}

- (void)setUpView {
    [self.view addSubview:self.toolbar];
    [self.view addSubview:self.pickerView];
    [self.pickerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.offset(12);
        make.right.offset(-12);
        make.centerY.equalTo(self.view.mas_centerY).offset(20);
    }];
}

#pragma mark - 设置默认时间
-(void)setDefaultInit{
    if (self.type == customType) {
        return;
    }
    self.yearRange = 50;
    //获取当前时间
    self.selectModel = [[MGCustomPickViewDateSelectModel alloc] initWithDate:[NSDate date]];
    self.startYear = self.selectModel.year - self.yearRange;
    [self setPickViewSelectDataSource];
}

#pragma mark - 设置 pickView 默认选中数据
- (void)setPickViewSelectDataSource {
    /// 获取天数
    self.dayRange = [self getDayWithMonth];
#pragma marl 根据选中时间定位对应位置
    /// 设置年
    [self.pickerView selectRow:self.selectModel.year - self.startYear inComponent:0 animated:NO];
    if (self.type == YearType){ /// 年
        [self.pickerView reloadAllComponents];
        return;
    }

    /// 设置月
    [self.pickerView selectRow:self.selectModel.month - 1 inComponent:1 animated:NO];
    if (self.type == YearMonthType){ /// 年月
        [self.pickerView reloadAllComponents];
        return;
    }

    /// 设置日
    [self.pickerView selectRow:self.selectModel.day - 1 inComponent:2 animated:NO];
    if (self.type == YearMonthDayType){ /// 年月日
        [self.pickerView reloadAllComponents];
        return;
    }
    /// 设置时
    [self.pickerView selectRow:self.selectModel.hour inComponent:3 animated:NO];
    if (self.type == YearMonthDayHourType){ /// 年月日时
        [self.pickerView reloadAllComponents];
        return;
    }
    /// 设置分
    [self.pickerView selectRow:self.selectModel.minute inComponent:4 animated:NO];
    [self.pickerView reloadAllComponents];
}

#pragma mark 设置最大值
- (void)setMaxDate:(NSDate *)maxDate {
    /// 最大值大于当前最大可选年份
    if (![self compareWithDate:maxDate]) {
        return;
    }
    _maxDate = maxDate;
    /// 最大值小于当前值，把最大值设置为当前值
    NSComparisonResult result = [self.selectModel.initializeDate compare:maxDate];
    if (result == NSOrderedDescending) {

        self.selectModel = [[MGCustomPickViewDateSelectModel alloc] initWithDate:maxDate];
        [self setPickViewSelectDataSource];
    }

}


#pragma mark 设置最小
- (void)setMinDate:(NSDate *)minDate {
    /// 最小值小于当前最小可选年份
    if (![self compareWithDate:minDate]) {
        return;
    }
    _minDate = minDate;
    /// 最小值大于当前值，把最小值设置为当前值
    NSComparisonResult result = [self.selectModel.initializeDate compare:minDate];
    if (result == NSOrderedAscending) {
        self.selectModel = [[MGCustomPickViewDateSelectModel alloc] initWithDate:minDate];
        [self setPickViewSelectDataSource];
    }

}

#pragma mark 设置默认选中值
- (void)setSelectDate:(NSDate *)selectDate {
    if (![self compareWithDate:selectDate]) {
        return;
    }
    if (![self compareWithDate:selectDate]) {
        return;
    }
    _selectDate = selectDate;
    if (self.maxDate != NULL) { /// 如果有最大值
        /// 设置选中年份大于最大值 将最大值设置为选中
        NSComparisonResult result = [selectDate compare:self.maxDate];
        if (result == NSOrderedDescending) {
            self.selectModel = [[MGCustomPickViewDateSelectModel alloc] initWithDate:self.maxDate];;
            [self setPickViewSelectDataSource];
        }
    }

    if (self.minDate != NULL) { /// 如果有最小值
        /// 设置选中年份小于最小值 将最小值设置为选中
        NSComparisonResult result = [self.selectDate compare:self.minDate];
        if (result == NSOrderedAscending) {
            self.selectModel = [[MGCustomPickViewDateSelectModel alloc] initWithDate:self.minDate];
            [self setPickViewSelectDataSource];
        }
    }
}

#pragma mark - 比较最大最小年份是否满足
/// 比较最大最小年份是否满足
/// - Parameters:
///   - date: 时间
///   - isMax: 是否是最大年份
- (BOOL)compareWithDate:(NSDate *)date{
    if (date == NULL) {
        return NO;
    }
    NSCalendar *calendar =[NSCalendar currentCalendar];
    NSInteger year = [calendar component:NSCalendarUnitYear fromDate:date];
    NSInteger currentYear = [calendar component:NSCalendarUnitYear fromDate:[NSDate date]];
    /// 最大值大于当前最大可选年份
    if ((year > currentYear + self.yearRange) || (year < currentYear - self.yearRange)) {
        return NO;
    }
    return YES;
}

#pragma mark - 选择对应月份的天数
- (NSInteger)getDayWithMonth{
    NSCalendar *ca = [NSCalendar currentCalendar];
    NSDateComponents *com = [[NSDateComponents alloc] init];
    com.year = self.selectModel.year;
    com.month = self.selectModel.month;
    NSDate *date = [ca dateFromComponents:com];
    NSInteger day = 0;
    if (date) {
        NSRange dayRange = [ca rangeOfUnit:NSCalendarUnitDay inUnit:NSCalendarUnitMonth forDate:date];
        day = dayRange.length;
    }
    return day;
}

#pragma mark -- UIPickerViewDataSource
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    if (self.type == customType) {
        return 1;
    }
    if (self.type == YearMonthDayHourMinuteType) {
        return 5;
    }
    else if (self.type == YearMonthDayHourType){
        return 4;
    }
    else if (self.type == YearMonthDayType){
        return 3;
    }
    else if (self.type == YearMonthType){
        return 2;
    }
    else if (self.type == YearType){
        return 1;
    }
    return 0;
}

//确定每一列返回的东西
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (self.type == customType) {
        return self.itemTitles.count;
    }
    switch (component) {
        case 0:{
            return self.yearRange * 2;
        }
            break;
        case 1:{
            return 12;
        }
            break;
        case 2:{
            return self.dayRange;
        }
            break;
        case 3:{
            return 24;
        }
            break;
        case 4:{
            return 60;
        }
            break;

        default:
            break;
    }
    return 0;
}

#pragma mark -- UIPickerViewDelegate
- (UIView*) pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    UILabel*label = [[UILabel alloc]init];
    label.font = [UIFont systemFontOfSize:15.0];
    label.textAlignment = NSTextAlignmentCenter;
    if (self.type == customType) {
        label.text = self.itemTitles[row];
        return label;
    }
    switch (component) {
        case 0:{
            label.text = [NSString stringWithFormat:@"%ld年",(self.startYear + row)];
        }
            break;
        case 1:{
            label.text = [NSString stringWithFormat:@"%.2ld月",(long)row+1];
        }
            break;
        case 2:{

            label.text = [NSString stringWithFormat:@"%.2ld日",(long)row+1];
        }
            break;
        case 3:{
            label.textAlignment = NSTextAlignmentRight;
            label.text = [NSString stringWithFormat:@"%.2ld",(long)row];
        }
            break;
        case 4:{
            label.textAlignment = NSTextAlignmentRight;
            label.text = [NSString stringWithFormat:@"%.2ld",(long)row];
        }
            break;

        default:
            break;
    }
    return label;
}

// 监听picker的滑动
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {

    if (self.type == customType) {
        self.result = self.itemTitles[row];
        return;
    }
    switch (component) {
        case 0:{ /// 年
            self.selectModel.year = self.startYear + row;
            if (self.type != YearMonthType && self.type != YearType) {  /// 更改日
                self.dayRange = [self getDayWithMonth];
                [self.pickerView reloadComponent:2];
            }
        }
            break;
        case 1:{ /// 月
            self.selectModel.month = row + 1;
            if (self.type != YearMonthType && self.type != YearType) { /// 更改日
                self.dayRange = [self getDayWithMonth];
                [self.pickerView reloadComponent:2];
            }
        }
            break;
        case 2:{ /// 日
            self.selectModel.day = row + 1;
        }
            break;
        case 3:{ /// 时
            self.selectModel.hour = row;
        }
            break;
        case 4:{ /// 分
            self.selectModel.minute = row;
        }
            break;

        default:
            break;
    }
    [self compareDate];
}

/// 比较设置最大和最小选择区域
- (void)compareDate {
    if (self.maxDate == NULL && self.minDate == NULL) {
        return;
    }
    NSDateFormatter *fromatter = [[NSDateFormatter alloc] init];
    if (self.type == YearMonthDayHourMinuteType) {
        self.result = [NSString stringWithFormat:@"%ld-%.2ld-%.2ld %.2ld:%.2ld", (long)self.selectModel.year, (long)self.selectModel.month, (long)self.selectModel.day, (long)self.selectModel.hour, (long)self.selectModel.minute];
        [fromatter setDateFormat:@"yyyy-MM-dd HH:mm"];
    }
    if (self.type == YearMonthDayHourType) {
        self.result = [NSString stringWithFormat:@"%ld-%.2ld-%.2ld %.2ld", (long)self.selectModel.year, (long)self.selectModel.month, (long)self.selectModel.day, (long)self.selectModel.hour];
        [fromatter setDateFormat:@"yyyy-MM-dd HH"];
    }
    if (self.type == YearMonthDayType) {
        self.result = [NSString stringWithFormat:@"%ld-%.2ld-%.2ld", (long)self.selectModel.year, (long)self.selectModel.month, (long)self.selectModel.day];
        [fromatter setDateFormat:@"yyyy-MM-dd"];
    }
    if (self.type == YearMonthType) {
        self.result = [NSString stringWithFormat:@"%ld-%.2ld", (long)self.selectModel.year, (long)self.selectModel.month];
        [fromatter setDateFormat:@"yyyy-MM"];
    }
    if (self.type == YearType) {
        self.result = [NSString stringWithFormat:@"%ld", (long)self.selectModel.year];
        [fromatter setDateFormat:@"yyyy"];
    }
    NSDate *date = [fromatter dateFromString:self.result];
    self.selectDate = date;
}


#pragma mark 事件
/// 取消
- (void)cancelItemAction {
    [self dismissViewControllerAnimated:YES completion:NULL];
}

/// 确认
- (void)sureItemAction {
    if (self.delegate && [self.delegate respondsToSelector:@selector(customPickView:result:type:)]) {
        [self.delegate customPickView:self result:self.result type:self.type];
    }
    [self dismissViewControllerAnimated:YES completion:NULL];
}

#pragma mark 懒加载
- (UIToolbar *)toolbar {
    if (!_toolbar) {
        _toolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 45)];
        _toolbar.clipsToBounds = YES;
        UIBarButtonItem *cancelItem = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(cancelItemAction)];
        cancelItem.width = 80;

        UIBarButtonItem *spaceItem=[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];

        UIBarButtonItem *sureItem = [[UIBarButtonItem alloc] initWithTitle:@"确认" style:UIBarButtonItemStyleDone target:self action:@selector(sureItemAction)];
        sureItem.width = 80;
        _toolbar.items= @[cancelItem,spaceItem,sureItem];
        _toolbar.barTintColor = [UIColor whiteColor];
        _toolbar.backgroundColor = [[UIColor lightGrayColor] colorWithAlphaComponent:0.4];
    }
    return _toolbar;
}

- (UIPickerView *)pickerView {
    if (!_pickerView) {
        _pickerView = [[UIPickerView alloc] init];
        _pickerView.backgroundColor = [UIColor whiteColor];
        _pickerView.dataSource = self;
        _pickerView.delegate = self;
    }
    return _pickerView;
}


@end

#pragma mark --------------- MGCustomPickViewDateSelectModel ---------------
@implementation MGCustomPickViewDateSelectModel

- (instancetype)initWithDate:(NSDate *)date {
    if (self = [super init]) {
        self.initializeDate = date;
       [self setDefaultInit];
    }
    return self;
}

- (void)setDefaultInit {
    NSCalendar *calendar0 = [NSCalendar currentCalendar];
    NSInteger unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay |
    NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    NSDateComponents *comps  = [calendar0 components:unitFlags fromDate:self.initializeDate];

    self.year= [comps year];
    self.month= [comps month];
    self.day= [comps day];
    self.hour= [comps hour];
    self.minute=[comps minute];
}

@end

